#include "../MultiReactor/Thread.h"
#include "../MultiReactor/CurrentThread.h"

#include <semaphore.h>


std::atomic_int Thread::numCreated_(0);
Thread::Thread(ThreadFunc func, const std::string &name)
    : started_(false)
    , joined_(false)
    , tid_(0)
    , func_(std::move(func))
    , name_(name)
{
    setDefaultName();
}

Thread::~Thread()
{
    if (started_ && !joined_)
    {
        thread_->detach();                                                  // thread类提供了设置分离线程的方法 线程运行后自动销毁（非阻塞）
    }
}


// C++ std::thread 中join()和detach()的区别：https://blog.nowcoder.net/n/8fcd9bb6e2e94d9596cf0a45c8e5858a
// 看看调用时机
void Thread::join()
{
    joined_ = true;
    thread_->join();
}

/*注意你是在主线程调用的start函数*/
void Thread::start()
{
    started_ = true;
    sem_t sem;
    sem_init(&sem, false, 0); 
    // 学一下lambda表达式 
    thread_ = std::shared_ptr<std::thread>(new std::thread([&]() {
        tid_ = CurrentThread::tid();                                        // 获取线程的tid值
        /*是在另一个线程操作的*/
        sem_post(&sem);
        func_(); 
    })); 
    // 这里必须等待获取上面新创建的线程的tid值
    // 
    sem_wait(&sem);                                            
}
void Thread::setDefaultName()
{
    int num = ++numCreated_;
    if (name_.empty())
    {
        char buf[32] = {0};
        snprintf(buf, sizeof buf, "Thread%d", num);
        name_ = buf;
    }
}
